package physics;

import gui.PlayersMap;

//physics class for gaming
public class Physics extends Thread{
	
	private boolean started = false;
	private PlayersMap map;
	private double energyX, energyY, m, dx, dy, vx, vy, a, v, dist, energy; //"a" is for the friction only 
	private final double g = 9.80665;
	private int timeQuantum = 20;
	private double time = (double) timeQuantum / 1000;
	
	//it starts the time
	public void startTime(){
		started = true;
		start();
	}
	
	//it stops the time
	public void stopTime(){
		started = false;
	}
	
	//constructor. it sets the map controlled by this physics
	public Physics(PlayersMap map){
		this.map = map;
		m = map.getBallMass();
	}
	
	//the body was affected with momentum 
	public void energyPassing(double eX, double eY){
		//the energy is the only information about the direction
		energyX += eX * map.getManoeuvrability();
		energyY += eY * map.getManoeuvrability();
		energy = Math.sqrt(energyX*energyX + energyY*energyY);
		v = Math.sqrt( (2*energy) / m );
	}
	
	//override for thread running
	public void run(){
		while(started){
			try {
				sleep(timeQuantum);
				double weight = m * g;
				double ff = weight * map.getFrictionalCoefficient();
				double cosFi, sinFi;

				if(energy != 0){
					cosFi = energyX / energy;
					sinFi = energyY / energy;
				}else{
					cosFi = 0;
					sinFi = 0;
				}
				
				dist = time*(v - ( (ff/m)*time )/2);
				v = v - (ff/m)*time;
				if( (dist > 0) && (v>0) ){
					
					energy = m*v*v/2;
					dx = dist * cosFi;
					vx = v * cosFi;
					energyX = energy * cosFi;
					
					dy = dist * sinFi;
					vy = v * sinFi;
					energyY = energy * sinFi;
				}else{
					dist = 0;
					v = 0;
					energy = 0;
					energyX = 0;
					energyY = 0;
					dx = 0;
					dy = 0;
				}

				map.moveBall(dx, dy);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}